<template>
  <view class="points">
    <view class="header">
      <text class="title">积分管理</text>
      <button class="btn-adjust" @click="showAdjustModal = true">批量调整</button>
    </view>
    
    <view class="stats-overview">
      <view class="stat-card">
        <text class="stat-number">{{ pointsStats.totalPoints }}</text>
        <text class="stat-label">总积分发放</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ pointsStats.totalUsers }}</text>
        <text class="stat-label">积分用户数</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ pointsStats.todayEarned }}</text>
        <text class="stat-label">今日获得</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ pointsStats.todayUsed }}</text>
        <text class="stat-label">今日消费</text>
      </view>
    </view>
    
    <view class="tabs">
      <text 
        class="tab" 
        :class="{ active: activeTab === 'records' }"
        @click="activeTab = 'records'"
      >
        积分记录
      </text>
      <text 
        class="tab" 
        :class="{ active: activeTab === 'users' }"
        @click="activeTab = 'users'"
      >
        用户积分
      </text>
      <text 
        class="tab" 
        :class="{ active: activeTab === 'expiration' }"
        @click="activeTab = 'expiration'"
      >
        过期管理
      </text>
    </view>
    
    <!-- 积分记录 -->
    <view v-if="activeTab === 'records'" class="records-section">
      <view class="filters">
        <input 
          class="search-input" 
          v-model="recordSearch" 
          placeholder="搜索用户或描述"
          @input="searchRecords"
        />
        <picker :value="typeIndex" :range="typeOptions" @change="onTypeChange">
          <view class="filter-picker">{{ typeOptions[typeIndex] }}</view>
        </picker>
      </view>
      
      <view class="record-list">
        <view v-for="record in pointsRecords" :key="record.id" class="record-item">
          <view class="record-info">
            <text class="user-name">{{ getUserDisplayName(record.user) }}</text>
            <text class="record-desc">{{ record.description }}</text>
            <text class="record-time">{{ formatDate(record.createdAt) }}</text>
          </view>
          
          <view class="record-amount">
            <text class="amount" :class="record.type === 'earn' ? 'earn' : 'spend'">
              {{ record.type === 'earn' ? '+' : '-' }}{{ record.amount }}
            </text>
            <text class="record-type">{{ getTypeText(record.type) }}</text>
          </view>
        </view>
      </view>
      
      <view class="pagination">
        <button 
          class="page-btn" 
          :disabled="recordPage <= 1"
          @click="loadPointsRecords(recordPage - 1)"
        >
          上一页
        </button>
        <text class="page-info">{{ recordPage }} / {{ recordTotalPages }}</text>
        <button 
          class="page-btn" 
          :disabled="recordPage >= recordTotalPages"
          @click="loadPointsRecords(recordPage + 1)"
        >
          下一页
        </button>
      </view>
    </view>
    
    <!-- 用户积分 -->
    <view v-if="activeTab === 'users'" class="users-section">
      <view class="filters">
        <input 
          class="search-input" 
          v-model="userSearch" 
          placeholder="搜索用户"
          @input="searchUsers"
        />
        <picker :value="sortIndex" :range="sortOptions" @change="onSortChange">
          <view class="filter-picker">{{ sortOptions[sortIndex] }}</view>
        </picker>
      </view>
      
      <view class="user-list">
        <view v-for="user in pointsUsers" :key="user.id" class="user-item">
          <view class="user-info">
            <text class="user-name">{{ user.nickname || user.phone || '未知用户' }}</text>
            <text class="user-level">等级: {{ user.memberLevel }}</text>
            <text class="user-join">注册: {{ formatDate(user.createdAt) }}</text>
          </view>
          
          <view class="user-points">
            <text class="points-balance">{{ user.points }}</text>
            <text class="points-label">积分</text>
          </view>
          
          <view class="user-actions">
            <button class="btn-adjust-user" @click="adjustUserPoints(user)">调整</button>
            <button class="btn-history" @click="viewUserHistory(user)">记录</button>
          </view>
        </view>
      </view>
      
      <view class="pagination">
        <button 
          class="page-btn" 
          :disabled="userPage <= 1"
          @click="loadPointsUsers(userPage - 1)"
        >
          上一页
        </button>
        <text class="page-info">{{ userPage }} / {{ userTotalPages }}</text>
        <button 
          class="page-btn" 
          :disabled="userPage >= userTotalPages"
          @click="loadPointsUsers(userPage + 1)"
        >
          下一页
        </button>
      </view>
    </view>
    
    <!-- 过期管理 -->
    <view v-if="activeTab === 'expiration'" class="expiration-section">
      <view class="expiration-stats">
        <view class="exp-stat">
          <text class="exp-number">{{ expirationStats.expiringSoon }}</text>
          <text class="exp-label">即将过期</text>
        </view>
        <view class="exp-stat">
          <text class="exp-number">{{ expirationStats.expiredToday }}</text>
          <text class="exp-label">今日过期</text>
        </view>
        <view class="exp-stat">
          <text class="exp-number">{{ expirationStats.totalExpired }}</text>
          <text class="exp-label">累计过期</text>
        </view>
      </view>
      
      <view class="expiring-list">
        <text class="section-title">即将过期积分</text>
        <view v-for="item in expiringPoints" :key="item.id" class="expiring-item">
          <view class="expiring-info">
            <text class="user-name">{{ getUserDisplayName(item.user) }}</text>
            <text class="points-amount">{{ item.amount }} 积分</text>
            <text class="expire-date">过期时间: {{ formatDate(item.expiresAt) }}</text>
          </view>
          <button class="btn-extend" @click="extendExpiration(item)">延期</button>
        </view>
      </view>
    </view>
    
    <!-- 调整积分弹窗 -->
    <view v-if="showAdjustModal || adjustingUser" class="modal-overlay" @click="closeAdjustModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">
            {{ adjustingUser ? '调整用户积分' : '批量调整积分' }}
          </text>
          <text class="modal-close" @click="closeAdjustModal">×</text>
        </view>
        <view class="modal-body">
          <view v-if="adjustingUser" class="user-info-section">
            <text class="current-points">当前积分: {{ adjustingUser.points }}</text>
          </view>
          
          <view class="form-group">
            <text class="form-label">调整类型</text>
            <picker :value="adjustTypeIndex" :range="adjustTypes" @change="onAdjustTypeChange">
              <view class="picker-view">{{ adjustTypes[adjustTypeIndex] }}</view>
            </picker>
          </view>
          
          <view class="form-group">
            <text class="form-label">调整数量</text>
            <input class="form-input" type="number" v-model="adjustForm.amount" placeholder="请输入积分数量" />
          </view>
          
          <view class="form-group">
            <text class="form-label">调整原因</text>
            <textarea class="form-textarea" v-model="adjustForm.reason" placeholder="请输入调整原因"></textarea>
          </view>
          
          <view v-if="!adjustingUser" class="form-group">
            <text class="form-label">用户筛选</text>
            <picker :value="userFilterIndex" :range="userFilterOptions" @change="onUserFilterChange">
              <view class="picker-view">{{ userFilterOptions[userFilterIndex] }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeAdjustModal">取消</button>
          <button class="btn-confirm" @click="confirmAdjustment">确认调整</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'records',
      
      // 统计数据
      pointsStats: {
        totalPoints: 0,
        totalUsers: 0,
        todayEarned: 0,
        todayUsed: 0
      },
      
      // 积分记录
      pointsRecords: [],
      recordSearch: '',
      recordPage: 1,
      recordTotalPages: 1,
      typeOptions: ['全部类型', '获得积分', '消费积分'],
      typeIndex: 0,
      
      // 用户积分
      pointsUsers: [],
      userSearch: '',
      userPage: 1,
      userTotalPages: 1,
      sortOptions: ['积分降序', '积分升序', '注册时间'],
      sortIndex: 0,
      
      // 过期管理
      expirationStats: {
        expiringSoon: 0,
        expiredToday: 0,
        totalExpired: 0
      },
      expiringPoints: [],
      
      // 调整积分
      showAdjustModal: false,
      adjustingUser: null,
      adjustForm: {
        amount: 0,
        reason: ''
      },
      adjustTypes: ['增加积分', '扣除积分'],
      adjustTypeIndex: 0,
      userFilterOptions: ['全部用户', '活跃用户', '新用户', '高积分用户'],
      userFilterIndex: 0
    }
  },
  
  onLoad() {
    this.loadPointsStats()
    this.loadPointsRecords()
  },
  
  watch: {
    activeTab(newTab) {
      if (newTab === 'records') {
        this.loadPointsRecords()
      } else if (newTab === 'users') {
        this.loadPointsUsers()
      } else if (newTab === 'expiration') {
        this.loadExpirationData()
      }
    }
  },
  
  methods: {
    async loadPointsStats() {
      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: 'http://localhost:3000/api/admin/points/stats',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (res.data.success) {
          this.pointsStats = res.data.data
        }
      } catch (error) {
        console.error('加载积分统计失败:', error)
      }
    },
    
    async loadPointsRecords(page = 1) {
      try {
        const token = uni.getStorageSync('token')
        const params = new URLSearchParams({
          page: page.toString(),
          limit: '20',
          search: this.recordSearch
        })
        
        if (this.typeIndex > 0) {
          const typeMap = { 1: 'earn', 2: 'spend' }
          params.append('type', typeMap[this.typeIndex])
        }
        
        const res = await uni.request({
          url: `http://localhost:3000/api/admin/points/records?${params.toString()}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (res.data.success) {
          this.pointsRecords = res.data.data.records || []
          this.recordPage = res.data.data.currentPage || 1
          this.recordTotalPages = res.data.data.totalPages || 1
        }
      } catch (error) {
        console.error('加载积分记录失败:', error)
      }
    },
    
    async loadPointsUsers(page = 1) {
      try {
        const token = uni.getStorageSync('token')
        const params = new URLSearchParams({
          page: page.toString(),
          limit: '20',
          search: this.userSearch
        })
        
        const sortMap = {
          0: 'points_desc',
          1: 'points_asc',
          2: 'created_at'
        }
        params.append('sort', sortMap[this.sortIndex])
        
        const res = await uni.request({
          url: `http://localhost:3000/api/admin/points/users?${params.toString()}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (res.data.success) {
          this.pointsUsers = res.data.data.users || []
          this.userPage = res.data.data.currentPage || 1
          this.userTotalPages = res.data.data.totalPages || 1
        }
      } catch (error) {
        console.error('加载用户积分失败:', error)
      }
    },
    
    async loadExpirationData() {
      try {
        const token = uni.getStorageSync('token')
        
        // 加载过期统计
        const statsRes = await uni.request({
          url: 'http://localhost:3000/api/admin/expiration/stats',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (statsRes.data.success) {
          this.expirationStats = statsRes.data.data
        }
        
        // 加载即将过期的积分
        const expiringRes = await uni.request({
          url: 'http://localhost:3000/api/admin/expiration/expiring',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (expiringRes.data.success) {
          this.expiringPoints = expiringRes.data.data || []
        }
      } catch (error) {
        console.error('加载过期数据失败:', error)
      }
    },
    
    searchRecords() {
      clearTimeout(this.recordSearchTimer)
      this.recordSearchTimer = setTimeout(() => {
        this.loadPointsRecords(1)
      }, 500)
    },
    
    searchUsers() {
      clearTimeout(this.userSearchTimer)
      this.userSearchTimer = setTimeout(() => {
        this.loadPointsUsers(1)
      }, 500)
    },
    
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.loadPointsRecords(1)
    },
    
    onSortChange(e) {
      this.sortIndex = e.detail.value
      this.loadPointsUsers(1)
    },
    
    adjustUserPoints(user) {
      this.adjustingUser = user
      this.adjustForm = {
        amount: 0,
        reason: ''
      }
    },
    
    viewUserHistory(user) {
      uni.navigateTo({
        url: `/pages/points/history?userId=${user.id}`
      })
    },
    
    async extendExpiration(item) {
      uni.showModal({
        title: '延期确认',
        content: '确定要将该积分延期30天吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const extendRes = await uni.request({
                url: `http://localhost:3000/api/admin/expiration/${item.id}/extend`,
                method: 'POST',
                header: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  days: 30
                }
              })
              
              if (extendRes.data.success) {
                uni.showToast({ title: '延期成功' })
                this.loadExpirationData()
              }
            } catch (error) {
              uni.showToast({ title: '延期失败', icon: 'none' })
            }
          }
        }
      })
    },
    
    closeAdjustModal() {
      this.showAdjustModal = false
      this.adjustingUser = null
      this.adjustForm = {
        amount: 0,
        reason: ''
      }
      this.adjustTypeIndex = 0
      this.userFilterIndex = 0
    },
    
    onAdjustTypeChange(e) {
      this.adjustTypeIndex = e.detail.value
    },
    
    onUserFilterChange(e) {
      this.userFilterIndex = e.detail.value
    },
    
    async confirmAdjustment() {
      if (!this.adjustForm.amount || this.adjustForm.amount <= 0) {
        uni.showToast({ title: '请输入有效的积分数量', icon: 'none' })
        return
      }
      
      if (!this.adjustForm.reason) {
        uni.showToast({ title: '请输入调整原因', icon: 'none' })
        return
      }
      
      try {
        const token = uni.getStorageSync('token')
        const adjustmentAmount = this.adjustTypeIndex === 0 ? this.adjustForm.amount : -this.adjustForm.amount
        
        let url, data
        if (this.adjustingUser) {
          // 单个用户调整
          url = `http://localhost:3000/api/admin/points/adjust/${this.adjustingUser.id}`
          data = {
            amount: adjustmentAmount,
            reason: this.adjustForm.reason
          }
        } else {
          // 批量调整
          url = 'http://localhost:3000/api/admin/points/batch-adjust'
          data = {
            amount: adjustmentAmount,
            reason: this.adjustForm.reason,
            userFilter: this.userFilterIndex
          }
        }
        
        const res = await uni.request({
          url,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data
        })
        
        if (res.data.success) {
          uni.showToast({ title: '调整成功' })
          this.closeAdjustModal()
          this.loadPointsStats()
          if (this.activeTab === 'records') {
            this.loadPointsRecords()
          } else if (this.activeTab === 'users') {
            this.loadPointsUsers()
          }
        }
      } catch (error) {
        uni.showToast({ title: '调整失败', icon: 'none' })
      }
    },
    
    getTypeText(type) {
      const typeMap = {
        'earn': '获得',
        'spend': '消费'
      }
      return typeMap[type] || type
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    },

    getUserDisplayName(user) {
      if (!user) return '未知用户'
      return user.nickname || user.phone || '未知用户'
    }
  }
}
</script>

<style scoped>
.points {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.btn-adjust {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.stats-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.stat-card {
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #007bff;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.tabs {
  display: flex;
  background: white;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx;
  font-size: 28rpx;
  color: #666;
  border-radius: 12rpx;
}

.tab.active {
  background-color: #007bff;
  color: white;
}

.filters {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.search-input {
  flex: 1;
  padding: 20rpx;
  background: white;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.filter-picker {
  padding: 20rpx;
  background: white;
  border-radius: 8rpx;
  font-size: 28rpx;
  min-width: 200rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.record-list, .user-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
  margin-bottom: 30rpx;
}

.record-item, .user-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.record-item:last-child, .user-item:last-child {
  border-bottom: none;
}

.record-info, .user-info {
  flex: 1;
}

.user-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.record-desc, .user-level {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.record-time, .user-join {
  font-size: 20rpx;
  color: #999;
}

.record-amount {
  text-align: right;
}

.amount {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.amount.earn {
  color: #28a745;
}

.amount.spend {
  color: #dc3545;
}

.record-type {
  font-size: 20rpx;
  color: #666;
}

.user-points {
  text-align: center;
  margin-right: 20rpx;
}

.points-balance {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #007bff;
  margin-bottom: 8rpx;
}

.points-label {
  font-size: 20rpx;
  color: #666;
}

.user-actions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.btn-adjust-user, .btn-history {
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.btn-adjust-user {
  background-color: #007bff;
}

.btn-history {
  background-color: #6c757d;
}

.expiration-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.exp-stat {
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.exp-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #ffc107;
  margin-bottom: 10rpx;
}

.exp-label {
  font-size: 24rpx;
  color: #666;
}

.expiring-list {
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.expiring-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.expiring-item:last-child {
  border-bottom: none;
}

.expiring-info {
  flex: 1;
}

.points-amount {
  display: block;
  font-size: 28rpx;
  color: #007bff;
  margin-bottom: 8rpx;
}

.expire-date {
  font-size: 20rpx;
  color: #dc3545;
}

.btn-extend {
  background-color: #ffc107;
  color: #333;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30rpx;
  padding: 30rpx;
}

.page-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.page-btn:disabled {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
}

.user-info-section {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.current-points {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.form-textarea {
  height: 120rpx;
  resize: vertical;
}

.picker-view {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-confirm {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style>